package com.yc.clouduser.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.clouduser.entity.User;
import com.yc.clouduser.mapper.UserMapper;
import com.yc.clouduser.service.IUserService;
import com.yc.clouduser.util.JwtUtil;
import com.yc.vcode.bean.Result;
import com.yc.vcode.bean.VcodeProperties;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserDo {

    @Autowired
    UserMapper userMapper;

    @Autowired
    VcodeProperties properties;

    @RequestMapping("login")
    public Result login(String uname, String upwd, HttpSession session){
        if("".equals(uname) || "".equals(upwd)){
            return new Result(0, "不能输入为空", null);
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName, uname);
        String md5 = DigestUtils.md5DigestAsHex(upwd.getBytes());
        lqw.eq(User::getPwd, md5);
        User user = userMapper.selectOne(lqw);
        if(user == null){
            return new Result(0, "用户或者密码错误", null);
        }else{
            if("封禁".equals(user.getStatus())){
                return new Result(0, "该用户已经封禁", null);
            }
            user.setPwd("");
            user.setEmail("");
            user.setCreateTime(null);
            //清除会话
            session.removeAttribute("vcode");
            //存入会话
            session.setAttribute(properties.getSessionKey(), user);
            return new Result(1, "登录成功", user);
        }
    }

    @RequestMapping("reg")
    public Result reg(String uname, String upwd, String email, HttpSession session){
        if("".equals(uname) || "".equals(upwd) || "".equals(email)){
            return new Result(0, "不能输入为空", null);
        }
        //验证email是否重复
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail, email);
        Long aLong = userMapper.selectCount(lqw);
        if(aLong > 0){
            return new Result(-1, "该邮箱已注册", null);
        }
        //验证name是否重复
        LambdaQueryWrapper<User> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(User::getName, uname);
        Long aLong1 = userMapper.selectCount(lqw1);
        if(aLong1 > 0){
            return new Result(-1, "该用户名已注册", null);
        }
        //开始注册
        User user = new User();
        user.setName(uname);
        String md5 = DigestUtils.md5DigestAsHex(upwd.getBytes());
        user.setPwd(md5);
        user.setEmail(email);
        user.setPic("http://127.0.0.1/cloud-other/image/e9160b01-5a30-4ea7-8fec-5863dba3bec9.jpg");
        user.setStatus("用户");
        userMapper.insert(user);
        //清除会话
        session.removeAttribute("ecode");
        return new Result(1, "注册成功", null);
    }

    //退出登录
    @RequestMapping("logout")
    Result logout(HttpSession session){
        try{
            session.invalidate();
            return new Result(1, "退出成功", null);
        }catch (Exception e){
            return new Result(0, "退出登录失败", null);
        }
    }

    @Autowired
    IUserService iUserService;

    //修改密码
    @RequestMapping("updatepwd")
    Result updatepwd(@RequestParam String oldPassword, @RequestParam String newPassword, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        return iUserService.updatepwd((Integer) user.get("id"), oldPassword, newPassword);
    }

    @RequestMapping("updateuser")
    Result updateuser(String name, String pic, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        Object id = user.get("id");
        String uid = id.toString();

        try {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();

            if("".equals(name)){
                //修改头像
                User user1 = userMapper.selectById(uid);
                user1.setPic(pic);
                userMapper.updateById(user1);
                user1.setPwd("");
                return new Result(1, "修改成功", user1);
            } else if ("".equals(pic)) {
                //只修改用户名
                lqw.eq(User::getName, name);
                Long aLong = userMapper.selectCount(lqw);
                if(aLong > 0){
                    return new Result(0, "用户名重复", null);
                }
                User user1 = userMapper.selectById(uid);
                user1.setName(name);
                userMapper.updateById(user1);
                user1.setPwd("");
                return new Result(1, "修改成功", user1);
            }else{
                //都修改
                lqw.eq(User::getName, name);
                Long aLong = userMapper.selectCount(lqw);
                if(aLong > 0){
                    return new Result(0, "用户名重复", null);
                }
                User user1 = userMapper.selectById(uid);
                user1.setName(name);
                user1.setPic(pic);
                userMapper.updateById(user1);
                user1.setPwd("");
                return new Result(1, "修改成功", user1);
            }
        }catch (Exception e){
            return new Result(-1 , "系统繁忙", null);
        }
    }

    //找回密码
    @RequestMapping("pwdemail")
    Result pwdemail(String email, HttpSession session){
        //判断有没有该邮箱
        System.out.println("email = " + email);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail, email);
        Long aLong = userMapper.selectCount(lqw);
        if(aLong == 0){
            return new Result(-1, "该邮箱未注册", null);
        }
        session.removeAttribute("pwdcode");
        return new Result(1, "验证成功", null);
    }

    @RequestMapping("updatenewpwd")
    Result updatenewpwd(String email,String pwd){
        try{
            //判断有没有该邮箱
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getEmail, email);
            Long aLong = userMapper.selectCount(lqw);
            if(aLong != 1){
                return new Result(-1, "该邮箱未注册", null);
            }
            User user = userMapper.selectOne(lqw);
            String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
            user.setPwd(md5);
            userMapper.updateById(user);
            return new Result(1, "修改成功", null);
        }catch (Exception e){
            return new Result(0, "系统异常", null);
        }
    }
}

